package net.qhzw.vip.qiyu.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.DtsBarManage;
import net.qhzw.vip.qiyu.entity.DtsBatteryManage;
import net.qhzw.vip.qiyu.entity.DtsUser;
import net.qhzw.vip.qiyu.entity.RepairMaint;
import net.qhzw.vip.qiyu.handler.MyException;
import net.qhzw.vip.qiyu.mapper.DtsBarManageMapper;
import net.qhzw.vip.qiyu.mapper.DtsBatteryManageMapper;
import net.qhzw.vip.qiyu.model.BigDataInfo;
import net.qhzw.vip.qiyu.service.DtsBarManageService;
import net.qhzw.vip.qiyu.service.DtsBatteryManageService;
import net.qhzw.vip.qiyu.util.MyDateUtils;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class DtsBarManageImpl extends ServiceImpl<DtsBarManageMapper, DtsBarManage> implements DtsBarManageService {

    @Autowired
    private DtsBarManageMapper dtsBarManageMapper;

    @Override
    public boolean addBar(DtsBarManage dtsBarManage) {
        dtsBarManage.setId(IdWorker.getId());
        dtsBarManage.setStatus((byte) 0);
        dtsBarManage.setIsDelete((byte) 0);
        //dtsBarManage.setCreateBy(SecurityUtils.getUserId());
        dtsBarManage.setCreated(new Date());
        return save(dtsBarManage);

    }

    @Override
    public boolean updateDtsBarManage(DtsBarManage dtsBarManage) {
        dtsBarManage.setCreated(new Date());
        return updateById(dtsBarManage);
    }

    @Override
    public Page<DtsBarManage> findByPage(Page<DtsBarManage> page, DtsBarManage dtsBarManage) {
        page.addOrder(OrderItem.desc("created"));
        page.addOrder(OrderItem.desc("fault_cupboarddoor_num"));
        Byte i = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String format1 = simpleDateFormat.format(new Date());
        if (dtsBarManage.getCreated() == null) {
            try {
                simpleDateFormat.parse(format1);
                //dtsBarManage.setCreated(simpleDateFormat.parse(format1));
                dtsBarManage.setCreated(new Date());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        LambdaQueryWrapper<DtsBarManage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsBarManage::getIsDelete, 0)
                .like(dtsBarManage != null && !StringUtils.isEmpty(dtsBarManage.getElectricCabinetName()), DtsBarManage::getElectricCabinetName, dtsBarManage.getElectricCabinetName())
                .eq(dtsBarManage != null && !StringUtils.isEmpty(dtsBarManage.getElectricCabinetCode()), DtsBarManage::getElectricCabinetCode, dtsBarManage.getElectricCabinetCode())
                .eq(dtsBarManage != null && !StringUtils.isEmpty(dtsBarManage.getStatus()), DtsBarManage::getStatus, dtsBarManage.getStatus())
                .apply(dtsBarManage.getCreated() != null,
                        "date_format(created,'%Y-%m-%d') = date_format({0},'%Y-%m-%d')", dtsBarManage.getCreated());


        //.orderByDesc(DtsBarManage::getProhibitedWarehouseNum)
        //.last("");
        if (dtsBarManage.getFlag() != null && dtsBarManage.getFlag() == 0) {
            wrapper.and((wrapper1) -> {
                wrapper1.gt(dtsBarManage != null && !StringUtils.isEmpty(dtsBarManage.getFlag()), DtsBarManage::getProhibitedWarehouseNum, 0)
                        .or()
                        .gt(dtsBarManage != null && !StringUtils.isEmpty(dtsBarManage.getFlag()), DtsBarManage::getFaultCupboarddoorNum, 0);
            });
        }
        Page<DtsBarManage> dtsBarPAge = page(page, wrapper);
        return dtsBarPAge;
    }

    @Transactional(rollbackFor = Exception.class)
    public void importRecharge(MultipartFile file) {
        log.error("【表格导入电柜,文件名称】: [{}]");
        ImportParams params = new ImportParams();
        //params.setTitleRows(1);//设置一级标题行为1行
        //params.setHeadRows(1);//设置header标题为1行
        List<DtsBarManage> dtsBarManageList = null;
        try {
            dtsBarManageList = ExcelImportUtil.importExcel(file.getInputStream(), DtsBarManage.class, params);
            System.out.println("【导入总数为】: [{}]" + dtsBarManageList.size());
            if (CollectionUtils.isEmpty(dtsBarManageList)) {
                throw new MyException("电柜表格不能为空");
            } else {
                //List<String> collect = dtsBarManageList.stream().filter(d -> d.getElectricCabinetCode() != null).map(w -> w.getElectricCabinetCode()).collect(Collectors.toList());
                List<DtsBarManage> list = list(new LambdaQueryWrapper<DtsBarManage>()
                        //.in(DtsBarManage::getElectricCabinetCode, collect)
                        .apply(
                                "date_format(created,'%Y-%m-%d') = date_format({0},'%Y-%m-%d')", new Date()));
                if (list != null) {
                    int delete = dtsBarManageMapper.delete(new LambdaQueryWrapper<DtsBarManage>()
                            //.in(DtsBarManage::getElectricCabinetCode, collect)
                            .apply(
                                    "date_format(created,'%Y-%m-%d') = date_format({0},'%Y-%m-%d')", new Date()));
                    //boolean remove = remove(null);

                }

                for (DtsBarManage dtsBarManage : dtsBarManageList) {
                    dtsBarManage.setId(IdWorker.getId());
                    dtsBarManage.setCreated(new Date());
                    dtsBarManage.setIsDelete((byte) 0);
                    if (dtsBarManage.getProhibitedWarehouseNum() == 0 && dtsBarManage.getFaultCupboarddoorNum() == 0) {
                        dtsBarManage.setStatus((byte) 1);
                    } else {
                        dtsBarManage.setStatus((byte) 0);
                    }
                    String onlnSts = dtsBarManage.getOnlnSts();
                    if (onlnSts.contains("在线")) {
                        dtsBarManage.setOnlnSts("1");
                    } else {
                        dtsBarManage.setOnlnSts("0");
                    }
                }
            }
            //listObjs(dtsBarManageList)
            boolean b = saveBatch(dtsBarManageList);
            if (b) {
                dtsBarManageMapper.updateByBeifen();
                dtsBarManageMapper.insertBeifen();
            }

        } catch (Exception e) {
            log.error("【表格导入失败】：");
            throw new MyException("表格导入失败");
        }

    }

    @Override
    public List<BigDataInfo> getCountFailureRt() {

        return dtsBarManageMapper.getCountFailureRt();
    }
}
